package flc.ast.fragment;

import android.app.Dialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.listener.OnPageChangeListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.MusicAlbumAllActivity;
import flc.ast.activity.PubAlbumActivity;
import flc.ast.activity.PubAlbumDetailActivity;
import flc.ast.activity.SelPictureActivity;
import flc.ast.adapter.AlbumAdapter;
import flc.ast.adapter.MusicAlbumAdapter;
import flc.ast.adapter.MyBannerAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.databinding.FragmentAlbumBinding;
import flc.ast.dialog.InputPasswordDialog;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.SPUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AlbumFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AlbumFragment extends BaseNoModelFragment<FragmentAlbumBinding> {

    private int selPosition = 1;
    private AlbumAdapter publicAlbumAdapter;
    private MusicAlbumAdapter musicAlbumAdapter;
    private Dialog myAddAlbumDialog;
    private EditText dialogAddAlbum;
    private String[] SecurityStr;
    private int position = 0;//选择的密保问题角标
    private Dialog mySetPasswordDialog;
    private EditText dialogSetPass, dialogSetPassAgain, dialogSetAnswer;
    private Dialog myForgetPasswordDialog;
    private EditText dialogForgetAnswer, dialogForgetPass, dialogForgetPassAgain;


    @Override
    protected int onCreate() {
        return R.layout.fragment_album;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);
        mDataBinding.ivPublicAlbumAdd.setOnClickListener(this);
        mDataBinding.tvAllAlbum.setOnClickListener(this);
        mDataBinding.ivPrivacyAlbum.setOnClickListener(this);
        mDataBinding.ivMusicAlbumAdd.setOnClickListener(this);
        mDataBinding.rvAlbumList.setLayoutManager(new GridLayoutManager(mContext, 2));
        publicAlbumAdapter = new AlbumAdapter();
        publicAlbumAdapter.setOnItemClickListener(this);
        musicAlbumAdapter = new MusicAlbumAdapter();
        musicAlbumAdapter.setOnItemClickListener(this);
        //设置密码弹框
        setPasswordDialog();
        //修改密码弹框
        forgetPasswordDialog();
        //添加相册弹框
        addAlbumDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvAllAlbum://全部相册
                switch (selPosition) {
                    case 0:
                        boolean isHave = SPUtil.getBoolean(mContext, Content.isHavePassword, false);
                        if (isHave) {
                            InputPasswordDialog inputPasswordDialog = new InputPasswordDialog(mContext);
                            inputPasswordDialog.setListener(new InputPasswordDialog.Listener() {
                                @Override
                                public void forgetPassword() {
                                    inputPasswordDialog.dismiss();
                                    dialogForgetAnswer.setText("");
                                    dialogForgetAnswer.setHint(SPUtil.getString(mContext, Content.myProblem, ""));
                                    dialogForgetPass.setText("");
                                    dialogForgetPassAgain.setText("");
                                    myForgetPasswordDialog.show();
                                }
                            });
                            inputPasswordDialog.show();
                        } else {
                            dialogSetAnswer.setHint(SecurityStr[position]);//默认密保
                            mySetPasswordDialog.show();
                        }
                        break;
                    case 1:
                        startActivity(PubAlbumActivity.class);
                        break;
                    case 2:
                        startActivity(MusicAlbumAllActivity.class);
                        break;
                }
                break;
            case R.id.ivPublicAlbumAdd://添加公开相册
                myAddAlbumDialog.show();
                break;
            case R.id.ivPrivacyAlbum://私密相册
                boolean isHave = SPUtil.getBoolean(mContext, Content.isHavePassword, false);
                if (isHave) {
                    InputPasswordDialog inputPasswordDialog = new InputPasswordDialog(mContext);
                    inputPasswordDialog.setListener(new InputPasswordDialog.Listener() {
                        @Override
                        public void forgetPassword() {
                            inputPasswordDialog.dismiss();
                            dialogForgetAnswer.setText("");
                            dialogForgetAnswer.setHint(SPUtil.getString(mContext, Content.myProblem, ""));
                            dialogForgetPass.setText("");
                            dialogForgetPassAgain.setText("");
                            myForgetPasswordDialog.show();
                        }
                    });
                    inputPasswordDialog.show();
                } else {
                    dialogSetAnswer.setHint(SecurityStr[position]);//默认密保
                    mySetPasswordDialog.show();
                }
                break;
            //设置密码弹框----------------------------------
            case R.id.ivDialogSetSwitch://切换密保问题
                if (position == 0) {
                    position++;
                } else if (position == 1) {
                    position++;
                } else if (position == 2) {
                    position = 0;
                }
                dialogSetAnswer.setHint(SecurityStr[position]);
                break;
            case R.id.ivDialogSetCancel://取消
                mySetPasswordDialog.dismiss();
                break;
            case R.id.ivDialogSetRight://确定
                if (TextUtils.isEmpty(dialogSetPass.getText().toString()) || dialogSetPass.getText().length() < 6) {
                    ToastUtils.showShort(R.string.please_input_6_password);//为空或者小于6
                } else if (TextUtils.isEmpty(dialogSetPassAgain.getText().toString()) || dialogSetPassAgain.getText().length() < 6) {
                    ToastUtils.showShort(R.string.please_right_new_password);//为空或者小于6
                } else if (!dialogSetPass.getText().toString().equals(dialogSetPassAgain.getText().toString())) {
                    ToastUtils.showShort(R.string.two_password_no_equest);//两次密码不一致
                } else if (TextUtils.isEmpty(dialogSetAnswer.getText().toString())) {
                    ToastUtils.showShort(R.string.please_input_password_answer);//密保答案为空
                } else {
                    SPUtil.putBoolean(mContext, Content.isHavePassword, true);
                    SPUtil.putString(mContext, Content.myPassword, dialogSetPass.getText().toString());
                    SPUtil.putString(mContext, Content.myProblem, SecurityStr[position]);
                    SPUtil.putString(mContext, Content.myAnswer, dialogSetAnswer.getText().toString());
                    ToastUtils.showShort(R.string.set_password_suc);
                    mySetPasswordDialog.dismiss();
                }
                break;
            //忘记密码弹框----------------------------------
            case R.id.ivDialogForgetCancel://取消
                myForgetPasswordDialog.dismiss();
                break;
            case R.id.ivDialogForgetRight://确认
                if (TextUtils.isEmpty(dialogForgetAnswer.getText().toString())) {
                    ToastUtils.showShort(R.string.please_input_password_answer);
                } else if (TextUtils.isEmpty(dialogForgetPass.getText().toString()) || dialogForgetPass.getText().length() < 6) {
                    ToastUtils.showShort(R.string.please_input_6_password);
                } else if (TextUtils.isEmpty(dialogForgetPassAgain.getText().toString()) || dialogForgetPassAgain.getText().length() < 6) {
                    ToastUtils.showShort(R.string.again_input_6_password);
                } else if (!dialogForgetPass.getText().toString().equals(dialogForgetPassAgain.getText().toString())) {
                    ToastUtils.showShort(R.string.two_password_no_equest);
                } else if (!dialogForgetAnswer.getText().toString().equals(SPUtil.getString(mContext, Content.myAnswer, ""))) {
                    ToastUtils.showShort(R.string.answer_def);
                } else {
                    SPUtil.putString(mContext, Content.myPassword, dialogForgetPass.getText().toString());
                    ToastUtils.showShort(R.string.update_password_suc);
                    myForgetPasswordDialog.dismiss();
                }
                break;
            //添加相册弹框
            case R.id.tvDialogAddAlbumCancel://取消
                myAddAlbumDialog.dismiss();
                break;
            case R.id.tvDialogAddAlbumRight://确定
                addAlbum();
                break;
            case R.id.ivMusicAlbumAdd://制作音乐相册
                startActivity(SelPictureActivity.class);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == publicAlbumAdapter) {
            String selId = publicAlbumAdapter.getItem(position).getId();
            if (TextUtils.isEmpty(selId)) {
                //添加公开相册
                dialogAddAlbum.setText("");
                myAddAlbumDialog.show();
            } else {
                //查看公开相册
                PubAlbumDetailActivity.albumId = selId;
                startActivity(PubAlbumDetailActivity.class);
            }
        } else if (adapter == musicAlbumAdapter) {
            String path = musicAlbumAdapter.getItem(position);
            if (TextUtils.isEmpty(path)) {
                startActivity(SelPictureActivity.class);
            }
        }
    }

    @Override
    protected void initData() {
        //密保问题
        SecurityStr = new String[]{getString(R.string.problem1), getString(R.string.problem2), getString(R.string.problem3)};//密保问题
        List<Integer> listImg = new ArrayList<>();
        listImg.add(R.drawable.aimg_1smxc);
        listImg.add(R.drawable.aimg_2gkxc);
        listImg.add(R.drawable.aimg_3yyxc);
        MyBannerAdapter bannerAdapter = new MyBannerAdapter(listImg);
        mDataBinding.banner.setStartPosition(2);
        mDataBinding.banner.setAdapter(bannerAdapter);//false不无限循环
        mDataBinding.banner.isAutoLoop(false);//false不自动轮播
        mDataBinding.banner.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selPosition = position;
                switch (position) {
                    case 0:
                        mDataBinding.tvAlbum.setText(getString(R.string.privacy_album));
                        mDataBinding.llPrivacyAlbum.setVisibility(View.VISIBLE);
                        mDataBinding.rvAlbumList.setVisibility(View.GONE);
                        mDataBinding.llPublicAlbumNoData.setVisibility(View.GONE);
                        mDataBinding.llMusicAlbumNoData.setVisibility(View.GONE);
                        break;
                    case 1:
                        mDataBinding.tvAlbum.setText(getString(R.string.public_album));
                        getPublicData();
                        break;
                    case 2:
                        mDataBinding.tvAlbum.setText(getString(R.string.music_album));
                        getMusicAlbumData();
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        getPublicData();
    }

    @Override
    public void onResume() {
        super.onResume();
        switch (selPosition) {
            case 1:
                getPublicData();
                break;
            case 2:
                getMusicAlbumData();
                break;
        }
    }

    private void getPublicData() {
        List<MyAlbumBean> listSp = AppSpUtils.getPublicAlbumList();
        if (listSp != null && listSp.size() > 1) {
            mDataBinding.rvAlbumList.setAdapter(publicAlbumAdapter);
            publicAlbumAdapter.setList(listSp);
            mDataBinding.rvAlbumList.setVisibility(View.VISIBLE);
            mDataBinding.llPrivacyAlbum.setVisibility(View.GONE);
            mDataBinding.llPublicAlbumNoData.setVisibility(View.GONE);
            mDataBinding.llMusicAlbumNoData.setVisibility(View.GONE);
        } else {
            if (listSp == null || listSp.size() == 0) {
                //准备新数据
                List<MyAlbumBean> list = new ArrayList<>();
                list.add(new MyAlbumBean("", "", new ArrayList<>()));
                AppSpUtils.savePublicAlbumList(list);
            }
            mDataBinding.rvAlbumList.setVisibility(View.GONE);
            mDataBinding.llPrivacyAlbum.setVisibility(View.GONE);
            mDataBinding.llPublicAlbumNoData.setVisibility(View.VISIBLE);
            mDataBinding.llMusicAlbumNoData.setVisibility(View.GONE);
        }
    }

    private void getMusicAlbumData() {
        List<String> listPath = new ArrayList<>();
        //获取文件夹下文件
        String path = PathUtils.getFilesPathExternalFirst() + Content.myMusicAlbum;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            listPath.add("");
            for (File file : files) {
                listPath.add(file.getPath());
            }
        }
        if (listPath.size() > 0) {
            musicAlbumAdapter.setList(listPath);
            mDataBinding.rvAlbumList.setAdapter(musicAlbumAdapter);
            mDataBinding.rvAlbumList.setVisibility(View.VISIBLE);
            mDataBinding.llPrivacyAlbum.setVisibility(View.GONE);
            mDataBinding.llPublicAlbumNoData.setVisibility(View.GONE);
            mDataBinding.llMusicAlbumNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvAlbumList.setVisibility(View.GONE);
            mDataBinding.llPrivacyAlbum.setVisibility(View.GONE);
            mDataBinding.llPublicAlbumNoData.setVisibility(View.GONE);
            mDataBinding.llMusicAlbumNoData.setVisibility(View.VISIBLE);
        }
    }

    //添加公开相册
    private void addAlbum() {
        String albumName = dialogAddAlbum.getText().toString();
        if (TextUtils.isEmpty(albumName)) {
            ToastUtils.showShort(R.string.please_input_album_name);
            return;
        }
        myAddAlbumDialog.dismiss();
        //准备数据
        List<MyAlbumBean> listSave = new ArrayList<>();
        listSave.add(new MyAlbumBean(TimeUtils.getNowString(), albumName, new ArrayList<>()));
        //保存数据
        List<MyAlbumBean> listSp = AppSpUtils.getPublicAlbumList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            AppSpUtils.savePublicAlbumList(listSp);
        } else {
            AppSpUtils.savePublicAlbumList(listSave);
        }
        getPublicData();
    }

    //添加相册弹框
    private void addAlbumDialog() {
        myAddAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_album, null);
        myAddAlbumDialog.setContentView(inflate);
        myAddAlbumDialog.setCancelable(false);
        //获取当前Activity所在的窗体
        Window dialogWindow = myAddAlbumDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.95);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogClose = inflate.findViewById(R.id.tvDialogAddAlbumCancel);
        TextView dialogCom = inflate.findViewById(R.id.tvDialogAddAlbumRight);
        dialogClose.setOnClickListener(this);
        dialogCom.setOnClickListener(this);
        dialogAddAlbum = inflate.findViewById(R.id.etDialogAddAlbum);
    }

    //设置密码弹框
    private void setPasswordDialog() {
        mySetPasswordDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_set_password, null);
        mySetPasswordDialog.setContentView(inflate);
        mySetPasswordDialog.setCancelable(false);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySetPasswordDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.95);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogClose = inflate.findViewById(R.id.ivDialogSetCancel);
        ImageView dialogSwitch = inflate.findViewById(R.id.ivDialogSetSwitch);
        ImageView dialogCom = inflate.findViewById(R.id.ivDialogSetRight);
        dialogClose.setOnClickListener(this);
        dialogSwitch.setOnClickListener(this);
        dialogCom.setOnClickListener(this);
        dialogSetPass = inflate.findViewById(R.id.etDialogSetPassword);
        dialogSetPassAgain = inflate.findViewById(R.id.etDialogSetAgain);
        dialogSetAnswer = inflate.findViewById(R.id.etDialogSetAnswer);
    }

    //修改密码弹框
    private void forgetPasswordDialog() {
        myForgetPasswordDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_forget_password, null);
        myForgetPasswordDialog.setContentView(inflate);
        myForgetPasswordDialog.setCancelable(false);
        //获取当前Activity所在的窗体
        Window dialogWindow = myForgetPasswordDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.95);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogClose = inflate.findViewById(R.id.ivDialogForgetCancel);
        ImageView dialogCom = inflate.findViewById(R.id.ivDialogForgetRight);
        dialogClose.setOnClickListener(this);
        dialogCom.setOnClickListener(this);
        dialogForgetAnswer = inflate.findViewById(R.id.etDialogForgetAnswer);
        dialogForgetPass = inflate.findViewById(R.id.etDialogForgetPassword);
        dialogForgetPassAgain = inflate.findViewById(R.id.etDialogForgetAgain);
    }

}